﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Dynamic;
using System.IO;
using Newtonsoft.Json;

namespace SQLite2JSON
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 3 || (args.Length == 4 && args[3] != "min") || args.Length > 4)
            {
                string exe = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location);
                Console.WriteLine("Usage: {0} sqlite.db \"SQL query string\" output.json [min]", exe);
                Console.WriteLine("Use 'con' for output file to output in console");
                return;
            }

            var connection = new SQLiteConnection(string.Format("Data Source={0}", args[0]));
            connection.Open();

            var cmd = connection.CreateCommand();
            cmd.CommandText = args[1];

            var reader = cmd.ExecuteReader();

            var objects = new List<ExpandoObject>();
            while (reader.Read())
            {
                var data = new ExpandoObject();

                var dictionary = (IDictionary<string, object>)data;

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    dictionary[reader.GetName(i)] = reader.GetValue(i);
                }

                objects.Add(data);
            }


            var formatting = Formatting.Indented;

            if (args.Length > 3 && args[3] == "min")
            {
                formatting = Formatting.None;
            }

            string jsonOfTest = JsonConvert.SerializeObject(objects, formatting);

            if (args[2] == "con")
            {
                Console.WriteLine(jsonOfTest);
            }
            else
            {
                File.WriteAllText(args[2], jsonOfTest);                
            }
        }
    }
}
